<?
class SmsTpl{
    public $le;
    public $s;
	public $smsid=0;
    public $tplVariable=array(
        "{dname}"     =>"[商家名称]",
        "{pname}"     =>"[预定产品]",
        "{tnum}"      =>"[预定数量]",
        "{code}"      =>"[凭证号]",
        "{begintime}" =>"[游玩/入住时间]",
        "{getaddr}"   =>"[取票信息]",
        "{sphone}"    =>"[客服电话]",
        "{place}"     =>"[集合地点]",
        "{link}"      =>"[详情及二维码链接]",
        "{maintain}"  =>"[预定天数]",
    );
	
	public $cancelBut = array(
		'{link}'
	);

    public $ptype_arr = array('A'=>'景区','B'=>'线路','C'=>'酒店','D'=>'商品');
    public function __construct($le,$s=null){
        $this->le=$le;
        $this->s=$s;
    }

    public function GetSmsTplFormat($did, $lid, $default=false, $ptype='A') {
        $defaultArr = array();
        $editArr = array();
        foreach($this->tplVariable as $key=>$var) {
            $defaultArr[$key] = '<span contenteditable="false" data-code="'.$key.'">'.$var.'</span>';
            $editArr[$key] = '<span contenteditable="false" data-code="'.$key.'">'.$var.'<a href="javascript:" class="del">X</a></span>';
        }

		
        $tplContent = $this->getTpl($did, $lid,$default, $ptype);
		//商家名称放后面
		$tplContent = str_replace('【{dname}】','',$tplContent).'【{dname}】';
        //$saved_content = str_replace(array_keys($defaultArr),array_values($defaultArr),$tplContent);
        $edit_content = str_replace(array_keys($editArr),array_values($editArr),$tplContent);
        return array($tplContent, $edit_content);
    }
	
	
	/**
     * 根据 pid 获取格式化模板内容
     * @param int $pid  产品ID
     * @return array
     */
	public function GetFormatSmsTpl($pid){
		$defaultArr = array();
		$editArr = array();
		foreach($this->tplVariable as $key=>$var) {
			$defaultArr[$key] = '<span contenteditable="false" data-code="'.$key.'">'.$var.'</span>';
			if(in_array($key,$this->cancelBut)){
				$editArr[$key] = '<span contenteditable="false" data-code="'.$key.'">'.$var.'<a href="javascript:" class="del">X</a></span>';
			}else{
				$editArr[$key] = '<span contenteditable="false" data-code="'.$key.'">'.$var.'</span>';
			}
				
		}
		if(empty($tplContent))	$tplContent = $this->GetTplByPid($pid);
		$edit_content = str_replace(array_keys($editArr),array_values($editArr),$tplContent);
		return $edit_content;
	}
	
	/**
     * 根据 pid 获取格式化模板内容
     * @param int $pid  产品ID
     * @return array
     */
	public function GetRevFormat($tpl){
		$tpl = strip_tags($tpl);
		foreach($this->tplVariable as $key=>$var) {
			$tpl=str_replace($var,$key,$tpl);
		}
		return $tpl;
	}
	
	
	/**
     * 根据 pid 获取模板内容
     * @param int $pid  产品ID
     * @return array
     */
	public function GetTplByPid($pid){
		$sql="SELECT id,cformat,pid FROM uu_sms_format WHERE pid=$pid LIMIT 1";
		$this->le->query($sql);
        $this->le->fetch_assoc();
		$smsid = $this->le->f('id');
		$this->smsid = $smsid;
		$defaultTpl='凭证号{code},您成功购买了{pname}:{tnum},消费日期:{begintime},{getaddr},此为入园凭证,请妥善保管。详情及二维码:{link}';
        return $smsid >0 ? $this->le->f("cformat") : $defaultTpl;
	}
	 
	 
	 
    /**
     * 根据供应商ID获取他可供应商的产品
     * @param int $did
     * @param bool $only_pid
     * @param int $lvl
     * @return array
     */
    public function GetDProcucts($did, $lvl=1, $lid=null, $ptype='')
    {
        $products = array();
        if($lvl==2) {
            $str_pstatus = "SELECT id FROM uu_products WHERE apply_did=$did AND p_status IN(0,2,3,4,5)";
            //echo $str_pstatus;
            $pid_arr = array();
            $this->le->query($str_pstatus);
            while($r=$this->le->fetch_assoc()) {
                $pid_arr[] = $r['id'];
            }
            $pid_str = implode(',', $pid_arr);

            $strGetTickets = "SELECT t.pid,l.p_type,l.title FROM uu_jq_ticket t"
                            . " ,uu_land l WHERE t.pid IN({$pid_str})";
            $strGetTickets .= !empty($lid) ? " AND l.id={$lid}" : '';
            $strGetTickets .= !empty($ptype) ? " AND p_type='{$ptype}'" : '';
            $strGetTickets .= " AND l.id=t.landid AND l.status=1";
//            echo $strGetTickets;
            $this->le->query($strGetTickets);
            while($rows=$this->le->fetch_assoc()) {
                $products[$rows['pid']] = $rows['p_type'];
            }
        }
        else {
            $strGetTickets = <<<SQL
  SELECT l.id, l.title,l.p_type, case when s.id THEN '已定制' ELSE '未定制' END AS flag  FROM uu_land l
  LEFT JOIN uu_jq_ticket t ON t.landid=l.id
  LEFT JOIN uu_sms_format s ON s.pid=t.pid
  WHERE l.apply_did={$did} AND l.status=1
  GROUP BY(l.id)
  ORDER BY l.p_type ASC
SQL;
            $this->le->query($strGetTickets);
            while($rows=$this->le->fetch_assoc()) {
                $products[] = $rows;
//                $products[$rows['id']]['p'] = $rows['p_type'];
//                $products[$rows['id']]['flag'] = $rows['flag'];
            }
        }
        //print_r($products);
        return $products;
    }

    /**
     * @param $cformat
     * @param int $did
     * @param int $lid
     * @return mixed
     */
    public  function editeTpl($cformat, $did, $lid=0, $ptype=''){
        if(!strlen($cformat) || !$did ) {
            return 0;
        }
        $cformat = strip_tags($cformat);
        $cformat = str_replace(array_values($this->tplVariable), array_keys($this->tplVariable), $cformat);
        //$cformat = trim($cformat);
        //clear all blank
        $cformat = str_replace(' ', '', $cformat);
        //全局配置
        if(!$lid) {
            $pid_arr = $this->GetDProcucts($did, 2, '', $ptype);
            $saved = $this->getTpl($did, 0, true);
            //内容没有修改
            if($cformat==$saved) {
                return 2;
            }
            $dtype = 1;
        }
        //指定商品
        else {
            $dtype = 0;
            $pid_arr = $this->GetDProcucts($did, 2, $lid);
        }
		
        $c = $this->_check($did, array_keys($pid_arr));
		print_r($c);
		exit;
        //print_r($c);return 1;
        //批量处理
        foreach($pid_arr as $pid=>$p_type) {
            if($c[$pid]['id']>0 && $c[$pid]['dtype'] < $dtype) continue;
            $this->_query($cformat,$did, $pid, $dtype, $p_type, $c[$pid]['id']);
        }
        return 1;
    }

    /**
     * 检测该供应商商指定产品是否已存在短信模板
     * @param $did 供应商ID
     * @param $pid 产品ID
     * @param int $dtype 是否为默认短信模板 1默认（全局设定）0指定
     * @return array
     */
    private function _check($did, $pid) {
        $pid = is_array($pid) ? implode(',', $pid) : $pid;
        $str="SELECT id, pid,dtype from uu_sms_format "
                ."WHERE did=$did AND pid IN ($pid)";
       // echo $str;
        $this->le->query($str);
        $s = array();
        while( $row = $this->le->fetch_assoc()) {
            $s[$row['pid']] = array(
                'id'=>$row['id'],
                'dtype'=>$row['dtype']
            );
        }
        return $s;
    }
    private function _query($cformat,$did,$pid,$dtype,$ptype, $tpl_id){
        if(!$tpl_id) {
            $str="INSERT uu_sms_format SET cformat='$cformat',did=$did,"
                ."pid=$pid,dtype=$dtype,ptype='{$ptype}'";
        }
        else {
            $str="UPDATE uu_sms_format SET cformat='$cformat', dtype=$dtype,"
                ."ptype='{$ptype}' WHERE id={$tpl_id}";
        }
//        echo $str;
        $this->le->query($str);
    }

    /**
     * 根据景区表ID获取一个产品ID
     * @param $lid
     * @return mixed
     */
    private function getPidByLandid($lid) {
        $str = "SELECT pid FROM uu_jq_ticket WHERE landid={$lid} LIMIT 1";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f('pid');
    }
    /**
     * 获取全局默认短信模板（当供应商商未配置短信模板时调用）
     * @return mixed
     */
    private function _getDefaultSmsTpl($ptype) {
        $ptype = strtolower($ptype);
        $file_name = ROOTPATH."d/module/static/default_sms_tpl_{$ptype}.txt";
        if(file_exists($file_name)) {
            return file_get_contents($file_name);
        }
        $str = "SELECT cformat FROM uu_sms_format WHERE did=0 and pid=0 LIMIT 1";
        $this->le->query($str);
        $this->le->fetch_assoc();
        return $this->le->f("cformat");
    }
    /**
     * 获取短信模板内容
     * @param $did 供应商商ID
     * @param $lid 景区表ID
     * @return mixed
     */
    public function getTpl($did, $lid=0, $default=false, $ptype='A'){

        if($default) {
            $str = "SELECT id,cformat FROM uu_sms_format WHERE did=$did and dtype=1 LIMIT 1";
        }
        elseif($lid>0) {
            $pid = $this->getPidByLandid($lid);
            //echo $pid;
            $str="SELECT id,cformat FROM uu_sms_format WHERE did=$did and pid=$pid LIMIT 1";
        }
        else {
            return false;
        }
        $this->le->query($str);
        $this->le->fetch_assoc();
        return $this->le->f('id')>0 ? $this->le->f("cformat")
                : $this->_getDefaultSmsTpl($ptype);
    }


}#EOF CLASS
